/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
  CCell, Cell, Table, TableBody, TableRow, Text, BlobInputList, TextArea, useTheme, Input, InputLine, SuffixInput, LineColumn, TableHead,
} from "customize-easy-ui-component";
import {
  CCellUnit, InspectRecordLayout, InternalItemProps, RepLink, useInputControlSure, useItemInputControl,
} from "../../common/base";
import {TailMenRowIspCheck} from "../../contain/rarelyVary";
import {useMeasureInpFilter} from "../../common/hooks";
import {EditStorageContext} from "../../StorageContext";
import {useUppyUpload} from "../../hook/useUppyUpload";
import {Each_ZdSetting, useContentTableViewer, useTableEditor} from "../../hook/useRepTableEditor";
import {floatInterception} from "../../../common/tool";

/*上面一半：是记录的编辑器。  针对同一块的报告页面部分。都整合在同一个文件内。
* */
export interface Props extends InternalItemProps {
  iAname?: string[];
}
export const itemA大板梁: string[] = ['_FILE_S挠度','仪器','仪器编','精度','大板备注','大板结果'];
export const LargeSlabBeam =
    React.forwardRef((
        {children, show, alone = true, refWidth, label, iAname,repId}: Props, ref
    ) => {
      const {modified,setModified,} =React.useContext(EditStorageContext) as any;
      const [getInpFilter] = useMeasureInpFilter(null, itemA大板梁, );
      const {inp, setInp,onSure} = useInputControlSure({ ref, });
      const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
        onSure({...inp, '_FILE_S挠度': upfile});
        !modified && setModified(true);
      }, [inp, modified,onSure,setModified]);
      const [uploadDom]=useUppyUpload({ repId:repId!,
             maxFile:5, onFinish, storeObj: inp?._FILE_S挠度
      });
      return (
          <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                               alone={alone} label={label!}>
            <Text variant="h5">{label}：</Text>
            <LineColumn>
              <InputLine label='仪器名称：'>
                <Input value={inp?.仪器 || ''}
                       onChange={e => setInp({...inp, 仪器: e.currentTarget.value || undefined})}/>
              </InputLine>
              <InputLine label='仪器编号：'>
                <Input value={inp?.仪器编 || ''}
                       onChange={e => setInp({...inp, 仪器编: e.currentTarget.value || undefined})}/>
              </InputLine>
              <InputLine label='仪器精度:'>
                <SuffixInput value={inp?.精度 || ''}
                             onSave={txt => setInp({...inp, 精度: txt || undefined})}
                >mm</SuffixInput>
              </InputLine>
            </LineColumn>
            检查部位示意图，ABC下的说明：
            <TextArea value={inp?.大板备注 || ''} rows={2}
                      onChange={e => setInp({...inp, 大板备注: e.currentTarget.value || undefined})}/>
            <hr/>
            <Text variant="h5">检查部位示意图：</Text>
            {uploadDom}
            <hr/>
            检验结果：
            <BlobInputList value={inp?.大板结果 || ''} rows={2} datalist={[ ]}
                             onListChange={v => setInp({...inp, 大板结果: v || undefined}) } />
            {children}
          </InspectRecordLayout>
      );
    });

export const config挠度=[['编号','n',90],['A测点数值','A',70],['B测点数值','B',70], ['C测点数值','C',70],
          ['AC点长度','l',80], ['挠度值','r',70] ] as Each_ZdSetting[];
const itemA挠度=['挠度表', ];
export const DeflectionCalc =
    React.forwardRef(({ children, show ,alone=true,refWidth,redId,nestMd}:InternalItemProps,  ref
    ) => {
      const [getInpFilter]=useMeasureInpFilter(null,itemA挠度, );
      const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
      const headview=<Text variant="h5">
        大板梁挠度检查-测量表。 单位：mm；
      </Text>;
      const [render部位汇总]=useTableEditor({inp, setInp,  headview,
        config: config挠度, table: '挠度表',  maxRf:4 });
      return (
          <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                               alone={alone}  label={'大板梁挠度检查-测量表'}>
            {render部位汇总}
          </InspectRecordLayout>
      );
    } );


/*下面一半：是报告的 展示。
* */
//增加自动计算的字段：A平均  z胀粗比率；
const config挠测量=[...config挠度.slice(0,5),  ['','d',0], ...config挠度.slice(5)]  as Each_ZdSetting[];
export const LargeSlabBeamVw = ({orc, rep}: { orc: any, rep: any }
) => {
  const theme = useTheme();
  //多出1列计算：生成新的表格: 但下面第二种办法，导致存储到后端数据库的表格多出字段，浪费存储了；
  const content= React.useMemo(()=>orc?.挠度表?.map((o: any)=>{
    const dpercent= floatInterception(Number(o?.l)/850, 3);
    return {...o, d: dpercent};
  }), [orc?.挠度表]);
  //orc?.挠度表?.forEach((o: any,i:number)=>{ o.d= floatInterception(Number(o?.l)/850, 2); orc?.挠度表?.splice(i,1,o); });
  const [renderHead,renderRows]=useContentTableViewer(config挠测量, content,true,true);
  return <>
    <div css={{"@media print": {paddingBottom: '3.5rem', pageBreakInside: 'avoid'}}}>
      <Text id='LargeSlabBeam' variant="h2" css={{
        textAlign: 'center', marginTop: '1rem',
      }}>大板梁挠度检查报告</Text>
      <div css={{display: 'flex', justifyContent: 'space-between'}}>
        <Text></Text>
        <Text>报告编号：{rep.isp.no}</Text>
      </div>
    </div>
    <Table fixed={  ["9%","29%","9%","22%","9%","%"] }
              css={{borderCollapse: 'collapse', "@media print": {marginTop: '-3.5rem'}}} tight miniw={800}>
      <TableBody>
        <RepLink rep={rep} tag={'LargeSlabBeam'}>
          <TableRow>
            <CCell>仪器名称</CCell><CCell>{orc.仪器??'／'}</CCell>
            <CCell>仪器编号</CCell><CCell>{orc.仪器编??'／'}</CCell>
            <CCell>仪器精度</CCell><CCellUnit unit='mm'>{orc.精度??'／'}</CCellUnit>
          </TableRow>
          <TableRow>
            <Cell colSpan={6}>
              检查部位示意图：<br/>
              <div css={{width: '90%', margin: 'auto', maxWidth:'30rem'}}>
                <div css={{display: 'flex', justifyContent: 'space-between'}}><Text>A</Text><Text>B</Text><Text>C</Text></div>
                <div css={{textAlign: 'center',border: '2px solid black',whiteSpace:'pre-wrap'}}>
                  {orc.大板备注 ?? '／'}
                </div>
              </div>
            </Cell>
          </TableRow>
          <TableRow>
            <Cell colSpan={6} split={true} css={{"@media print": {height: undefined}, padding: 0}}>
              {!(orc?._FILE_S挠度?.length>0) && <Text css={{textAlign: 'center',display:'block'}}> / </Text>}
              {orc?._FILE_S挠度?.map(({name, url}: any, i: number) => {
                return <div key={i} css={{"@media print": {pageBreakInside: 'avoid' } }}>
                  {i>0 && <hr/>}
                  <div css={{display: 'flex',justifyContent: 'space-around',alignItems: 'center',}}>
                    { url &&
                        <img src={process.env.REACT_APP_OSS_ENDP+url} alt={url}
                             css={{
                               maxHeight: '14cm',
                               maxWidth: '-webkit-fill-available',
                               [theme.mediaQueries.lg]: {maxHeight: '18cm', maxWidth: undefined},
                               "@media print": {maxHeight: '86vh', maxWidth: '100%'},
                             }}
                        />
                    }
                  </div>
                </div>
              }) }
            </Cell>
          </TableRow>
        </RepLink>
      </TableBody>
    </Table>
    <Table fixed={ ["%","12%","12%","12%","13%","13%","14%"] } css={{borderCollapse: 'collapse'}} tight miniw={800}>
      <TableHead>
        <RepLink rep={rep} tag={'DeflectionCalc'}>
          <TableRow id='DeflectionCalc'>
            <CCell>编号</CCell><CCell>A测点数值（mm）</CCell><CCell>B测点数值（mm）</CCell><CCell>C测点数值（mm）</CCell>
            <CCell>AC点长度（mm）</CCell><CCell>AC长度/850（mm）</CCell><CCell>挠度值（mm）</CCell>
          </TableRow>
        </RepLink>
      </TableHead>
      <TableBody>
        <RepLink rep={rep} tag={'DeflectionCalc'}>
         {renderRows}
        </RepLink>
      </TableBody>
    </Table>
    <TailMenRowIspCheck orc={orc} rep={rep} href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/ProjectList#ProjectList`}>
      <RepLink rep={rep} tag={'LargeSlabBeam'}>
        <TableRow>
          <Cell split={true} colSpan={2}><div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
            检验结果：<br/>
            {orc.大板结果 || '／'}
          </div></Cell>
        </TableRow>
      </RepLink>
    </TailMenRowIspCheck>
  </>;
};
